
import BaseAd from "../base/BaseAd";
import { SDKState, FunctionType } from "../SDKConfig";
/**
 * https://developers.weixin.qq.com/minigame/dev/api/ad/wx.createInterstitialAd.html
 */
export default class WXInterstitialAd extends BaseAd {

    protected instance: wx.InterstitialAd;

    open(adID: string, func: (r: number) => void) {
        // if (this.state == SDKState.open) {
        //     return;
        // }
        // if (this.state == SDKState.loading) {
        //     return;
        // }
        this.callback = func;
        console.log('BaseInterstitialAd showAd adUnitID ', this.adUnitID)
        this.state = SDKState.loading;
        this.destroy()
        this.create(adID)
        this.show()
    }

    onLoad() {
        console.log(' 插屏广告加载成功')
        this.setState(SDKState.loadSucess)
        if (this.callback) {
            this.callback(1)
        }
        // this.show()
    }

    onError(err) {
        console.log(' 插屏广告加载失败 ', err)
        this.setState(SDKState.loadFail)
        if (this.callback) {
            this.callback(0)
        }
    }

    onClose() {
        this.setState(SDKState.close)
    }

    load() {
        if (this.instance) {
            this.instance.load()
        }
    }

    show() {
        if (this.instance) {
            this.setState(SDKState.open)
            this.instance.show()
        }
    }

    destroy() {
        if (this.instance) {
            this.instance.offLoad(this.getFunc(FunctionType.onLoad))
            this.instance.offClose(this.getFunc(FunctionType.onClose))
            this.instance.offError(this.getFunc(FunctionType.onError))
            this.instance.destroy()
            this.instance = null;
        }
    }

    protected create(id) {
        this.adUnitID = id;
        // 创建插屏广告实例，提前初始化
        if (!this.instance) {
            this.instance = wx.createInterstitialAd({
                adUnitId: id
            })
            this.instance.onLoad(this.getFunc(FunctionType.onLoad))
            this.instance.onError(this.getFunc(FunctionType.onError))
            this.instance.onClose(this.getFunc(FunctionType.onClose))
        }
    }
}
